import CusDatePicker from "@/components/CusDatePicker";
import { PageWrapper } from "@/components/PageWrapper";
import { Title } from "@/components/Title";
import LittleTitle from "@/components/Title/littleTitle";
import { Button, message, Popover, Select, Tabs } from "antd";
import dayjs from 'dayjs';
import { useCallback, useEffect, useState } from "react";
import styled from "styled-components";
import icon_setting from "@/assets/icons/icon-set.png";
import icon_download from "@/assets/icons/icon-download.png";
import SimpleColumnSelector from "@/components/ColumnSelectorFilter/simpleSelector";
import styles from "./index.less";
import { BorderRedBtn, TableOptBtn } from "@/components/Button";
import { RedPlus } from "@/components/Icon";
import FreeTable from "@/components/Table/freeTable";
import EditEventStrategy from "./editEvent";
import {
  deleteMacrography,
  deleteSellerIncom,
  fixed_export,
  getIndexConfig,
  macro_export,
  macro_selectList,
  monetary_export,
  queryBroker,
  queryBrokerDate,
  queryMacroBroker,
  queryMacroBrokerDate,
  queryMonetaryDate,
  queryMonetaryReportTable,
  selectList,
  setIndexConfig,
} from "./service";
import icon_delete from "@/assets/icons/icon_delete.png";
import icon_edit from "@/assets/icons/icon_edit.png";
import { exportExcel, isAuthored } from "@/utils/utils";
import ErrorModal from "@/components/CommonComponents/ErrorModals";
import icon_error from "@/assets/icons/icon-warning.png";
import CusSelectMulti from "@/components/MultiSelect";
import cn from "classnames";
import EventEmptyCom from "@/components/FOF/EventEmpty";

const TABS = [
  {
    title: "卖方固收组观点汇总",
    key: "1",
  },
  {
    title: "卖方宏观组观点汇总",
    key: "2",
  },
  {
    title: "货币政策执行报告对比",
    key: "3",
  },
];

export const DRAWER_TITLE = {
  "1": "新增卖方固收组观点",
  "2": "新增卖方宏观组观点",
  "3": "新增货币政策执行报告",
};

let fixedColumnOptions = [
  // { label: "多空判断(短)", value: "moreEmptyShort" },
  // { label: "多空判断(中)", value: "moreEmptyMiddle" },
  // { label: "核心观点", value: "coreContent" },
  // { label: "分析逻辑", value: "logic" },
  // { label: "利率/衍生品策略", value: "deriveTactics" },
  // { label: "信用策略", value: "creditTactics" },
  // { label: "转债策略", value: "convertibleTactics" },
  // { label: "日期", value: "createdTime" },
];

let macroColumnOptions = [
  // { label: "市场观点", value: "moreEmptyShort" },
  // { label: "分析逻辑", value: "moreEmptyMiddle" },
  // { label: "日期", value: "coreContent" },
];

const flagOptions = [
  { label: "多", value: "0" },
  { label: "空", value: "1" },
];
interface tabProps {
  title: string;
  key: string;
}

const { TabPane } = Tabs;

let fixedConfigName = "";
let fixedConfigId = "";
let macroConfigName = "";
let macroConfigId = "";
const FIXED_CONFIG_CODE = "SELLER_FIXED_INCOME_FORM_CONFIG";
const MACRO_CONFIG_CODE = "SELLER_MACROGRAPHY_FORM_CONFIG";

let CLICK_FLAG = 0; // 判断是否是点击状态

export function SellerStrategy() {
  const [currentKey, setCurrentKey] = useState("1");
  const [start, setStart] = useState(null);
  const [macroStart, setMacroStart] = useState(null);
  const [end, setEnd] = useState(null);
  const [macroEnd, setMacroEnd] = useState(null);
  const [saveParams, setSaveParams] = useState({
    broker: undefined,
    macroBroker: undefined,
    shortFlag: undefined, //  0-多，1-空
    middleFlag: undefined,
  });
  const [checkedColumnKeys, setCheckedColumnKeys] = useState([]); // 选中的自定义列key
  const [checkedMacroColumnKeys, setCheckedMacroColumnKeys] = useState([]); // 选中的自定义列key
  const [popoverVisible, setPopoverVisible] = useState(false);
  const [macroPopoverVisible, setMacroPopoverVisible] = useState(false);
  const [fixedIncomeList, setFixedIncomeList] = useState([]);
  const [macroList, setMacroList] = useState([]);
  const [loadingBroker, setLoadingBroker] = useState(false);
  const [loadingMacroBroker, setLoadingMacroBroker] = useState(false);
  const [loadingMonetary, setLoadingMonetary] = useState(false);
  const [brokerOptions, setBrokerOptions] = useState([]); // 固收券商
  const [brokerMacroOptions, setBrokerMacroOptions] = useState([]); // 宏观券商
  const [fixedColumns, setFixedColumns] = useState([]);
  const [macroColumns, setMacroColumns] = useState([]);
  const [baseDrawerProps, setBaseDrawerProps] = useState(
    {} as { [propsName: string]: any }
  ); // 打开drawer传递的参数

  const [deleteInfo, setDeleteInfo] = useState<any>({
    modalVisible: false,
    errorMsg: "",
    deleteId: -1,
    deleteType: "0",
  });

  const [monetaryOptions, setMonetaryOptions] = useState([]); // 货币可选项
  const [selectMonetaryOptions, setSelectMonetaryOptions] = useState([]); // 选择项
  const [monetaryReportTable, setMonetaryReportTable] = useState([]); // 货币政策列表数据
  const [monetaryColumns, setMonetaryColumns] = useState([]);

  const [maxIndex, setMaxIndex] = useState(-1);

  // 计算dom高度
  const calcDomHeight = useCallback((idName: string) => {
    const height = targetDom(idName).offsetHeight;
    return height;
  }, []);

  const handleScroll = useCallback(
    (event: any) => {
      if (CLICK_FLAG === 1) return;
      let scrollTop = Math.ceil(event.target.scrollTop); //滚动条滚动高度
      const child_1 = calcDomHeight("child_1");
      const child_2 = calcDomHeight("child_2");

      if (scrollTop > child_1 + child_2 + 32) {
        setCurrentKey("3");
      } else if (scrollTop > child_1) {
        setCurrentKey("2");
      } else {
        setCurrentKey("1");
      }
    },
    [calcDomHeight]
  );

  // 获取对应dom
  const targetDom = (idName: string): any => {
    return document.getElementById(idName);
  };

  useEffect(() => {
    const container = targetDom("seller_box");
    container && container.addEventListener("scroll", handleScroll);
    return () => {
      container && container.removeEventListener("scroll", handleScroll);
    };
  }, [handleScroll]);

  useEffect(() => {
    // 重置
    targetDom("child_3").style.paddingBottom = 0;
    const boxHeight = calcDomHeight("seller_box");
    const child_3 = calcDomHeight("child_3");
    // console.log(child_3, targetDom("child_3"), boxHeight);
    if (child_3 + 32 < boxHeight) {
      targetDom("child_3").style.paddingBottom =
        boxHeight - child_3 - 32 + "px";
    }
  }, [monetaryReportTable, macroList, fixedIncomeList]);

  /**
   *
   * @param target 滚动到的目标位置
   * @param current 当前滚动条位置
   * @param dom 滚动目标
   */
  const stepForward = (target: number, current: number, dom: HTMLElement) => {
    let speed = 8;
    let time = 1;
    let timer = setInterval(() => {
      // console.log(target, current);
      time++;
      if (target < current) {
        // 上移
        dom.scrollTop -= speed * time;
        if (dom.scrollTop < speed || dom.scrollTop < target) {
          dom.scrollTop = target;
          clearInterval(timer);
          timer = null;
          CLICK_FLAG = 0;
        }
      } else if (target > current) {
        // 下移
        dom.scrollTop += speed * time;
        if (dom.scrollTop > target - 100) {
          dom.scrollTop = target;
          clearInterval(timer);
          timer = null;
          CLICK_FLAG = 0;
        }
      } else {
        clearInterval(timer);
        timer = null;
        CLICK_FLAG = 0;
      }
    }, 30);
  };
  // 点击切换后计算滚动逻辑
  const handleClickScroll = (key: "1" | "2" | "3") => {
    const child_1 = calcDomHeight("child_1");
    const child_2 = calcDomHeight("child_2");
    if (key === "1") {
      stepForward(
        0,
        targetDom("seller_box").scrollTop,
        targetDom("seller_box")
      );
    } else if (key === "2") {
      stepForward(
        child_1 + 32,
        targetDom("seller_box").scrollTop,
        targetDom("seller_box")
      );
    } else if (key === "3") {
      stepForward(
        child_1 + child_2 + 64,
        targetDom("seller_box").scrollTop,
        targetDom("seller_box")
      );
    }
  };

  const callback = (key: "1" | "2" | "3") => {
    CLICK_FLAG = 1;
    const container = targetDom("seller_box");
    container && container.removeEventListener("scroll", handleScroll);
    setCurrentKey(key);
    handleClickScroll(key);
  };

  // 保存查询条件
  const handleDate = (e: any, type: string, style: string) => {
    if (type === "start") {
      style === "fixed" ? setStart(e) : setMacroStart(e);
    } else {
      style === "fixed" ? setEnd(e) : setMacroEnd(e);
    }
  };

  // 修改下拉框
  const onChange = (val: string, key: string) => {
    setSaveParams((state) => {
      return {
        ...state,
        [key]: val || undefined,
      };
    });
  };

  // 改变列
  const changeColumns = (columns) => {
    setCheckedColumnKeys(columns);
    const configs = fixedColumnOptions.map((item) => {
      if (columns.includes(item.value)) {
        item.checked = true;
      } else {
        item.checked = false;
      }
      return item;
    });
    let params = {
      id: fixedConfigId,
      configName: fixedConfigName,
      configCode: FIXED_CONFIG_CODE,
      configs: JSON.stringify(configs),
    };
    setIndexConfig(params).then((res) => {
      console.log(res);
      if (res?.code == 0) {
        message.success("操作成功！");
        getConfig(FIXED_CONFIG_CODE);
      } else {
        message.error("操作失败！");
      }
    });
  };

  const changeMacroColumns = (columns) => {
    setCheckedMacroColumnKeys(columns);
    const configs = macroColumnOptions.map((item) => {
      if (columns.includes(item.value)) {
        item.checked = true;
      } else {
        item.checked = false;
      }
      return item;
    });
    let params = {
      id: macroConfigId,
      configName: macroConfigName,
      configCode: MACRO_CONFIG_CODE,
      configs: JSON.stringify(configs),
    };
    setIndexConfig(params).then((res) => {
      console.log(res);
      if (res?.code == 0) {
        message.success("操作成功！");
        getConfig(MACRO_CONFIG_CODE);
      } else {
        message.error("操作失败！");
      }
    });
  };

  const exportData = async (style: string) => {
    if (style === "fixed") {
      let fieldList = JSON.parse(
        JSON.stringify(fixedColumns)
          .replace(/title/g, "name")
          .replace(
            /convertibleTactics|coreContent|creditTactics|deriveTactics|moreEmptyMiddle|logic|moreEmptyShort/g,
            (m) => (m += "Str")
          )
          .replace(/createdTime/g, "createDate")
      );
      fieldList.splice(
        fieldList.findIndex((v) => v.key === "option"),
        1
      );
      const response: Blob = await fixed_export({
        broker: saveParams.broker,
        middleFlag: saveParams.middleFlag,
        shortFlag: saveParams.shortFlag,
        fieldList,
        endDate: end ? dayjs(end).format("YYYY-MM-DD") : "",
        startDate: start ? dayjs(start).format("YYYY-MM-DD") : "",
      });
      exportExcel(response, "卖方固收组观点汇总");
    } else if (style === "macro") {
      let fieldList = JSON.parse(
        JSON.stringify(macroColumns)
          .replace(/title/g, "name")
          .replace(/marketContent|logic/g, (m) => (m += "Str"))
          .replace(/createdTime/g, "createDate")
      );
      fieldList.splice(
        fieldList.findIndex((v) => v.key === "option"),
        1
      );
      const response: Blob = await macro_export({
        broker: saveParams.broker,
        fieldList,
        endDate: macroEnd ? dayjs(macroEnd).format("YYYY-MM-DD") : "",
        startDate: macroStart ? dayjs(macroStart).format("YYYY-MM-DD") : "",
      });
      exportExcel(response, "卖方宏观组观点汇总");
    } else {
      const response: Blob = await monetary_export({
        reportDates: selectMonetaryOptions,
      });
      exportExcel(response, "货币政策执行报告对比");
    }
  };

  //新增事件
  const addEvent = (b: boolean, type?: "1" | "2" | "3", record?: any = {}) => {
    setBaseDrawerProps({
      title: type,
      visible: b,
      ...record,
    });
  };

  // 删除
  const deleteList = () => {
    if (deleteInfo.deleteType === "1") {
      // 固收
      deleteSellerIncom({ id: deleteInfo.deleteId }).then((res) => {
        if (res?.code === "0") {
          message.success(res.msg);
          handleQueryFixAssets();
          setDeleteInfo({ modalVisible: false });
        } else if (res?.code === "1") {
          message.error(res?.data?.message);
        }
      });
    } else if (deleteInfo.deleteType === "2") {
      // 宏观
      deleteMacrography({ id: deleteInfo.deleteId }).then((res) => {
        if (res?.code === "0") {
          message.success(res.msg);
          handleQueryMacro();
          setDeleteInfo({ modalVisible: false });
        } else if (res?.code === "1") {
          message.error(res?.data?.message);
        }
      });
    }
  };

  const genColumns = (type: "1" | "2" | "3") => {
    if (isAuthored("EDIT_DELETE")) {
      return [
        {
          title: "操作",
          key: "option",
          valueType: "option",
          width: 36,
          fixed: true,
          render: (item: any, record: any) => {
            return (
              <div
                style={{
                  display: "flex",
                  flexDirection: "column",
                  alignItems: "center",
                }}
              >
                <TableOptBtn
                  img={icon_edit}
                  style={{ marginBottom: "4px", marginTop: "3px" }}
                  text=""
                  onClick={() => {
                    addEvent(true, type, record);
                  }}
                />
                <TableOptBtn
                  img={icon_delete}
                  style={{ marginBottom: "4px", marginTop: "3px" }}
                  text=""
                  onClick={() => {
                    // deleteList(type, record.id);
                    setDeleteInfo({
                      modalVisible: true,
                      errorMsg: "确认要删除该模块？",
                      deleteId: record.id,
                      deleteType: type,
                    });
                  }}
                />
              </div>
            );
          },
        },
        {
          title: "券商",
          key: "broker",
          dataIndex: "broker",
          width: 60,
          fixed: true,
          render: (text: string) => (
            <div style={{ width: 60, whiteSpace: "pre-wrap" }}>{text}</div>
          ),
        },
      ];
    } else {
      return [
        {
          title: "券商",
          key: "broker",
          dataIndex: "broker",
          ellipsis: true,
          width: 60,
          fixed: true,
          render: (text: string) => (
            <div style={{ width: 60, whiteSpace: "pre-wrap" }}>{text}</div>
          ),
        },
      ];
    }
  };

  const getConfig = (configCode: string) => {
    getIndexConfig({ configCode }).then((res) => {
      let checkedItems = [];

      let configs = res?.data[0]?.configs;
      if (configCode === FIXED_CONFIG_CODE) {
        let tmpColumns: any = genColumns("1");
        fixedConfigName = res?.data[0]?.configName;
        fixedConfigId = res?.data[0]?.id;
        // wtf
        fixedColumnOptions = [
          ...configs?.map((item) => {
            if (item.checked) {
              checkedItems.push(item.value);
              tmpColumns.push({
                title: item.title,
                dataIndex: item.value,
                key: item.value,
                width:
                  item.title === "日期"
                    ? 120
                    : ["核心观点", "分析逻辑"]?.includes(item.title)
                    ? "calc(100% - 100px)"
                    : "calc(50% - 50px)",
                render:
                  item.title === "日期"
                    ? undefined
                    : (text: string) => (
                        <div
                          className={cn(
                            styles.editorDisplay,
                            "editor-description"
                          )}
                          style={{
                            minWidth: ["核心观点", "分析逻辑"]?.includes(
                              item.title
                            )
                              ? "30vw"
                              : "15vw",
                          }}
                          dangerouslySetInnerHTML={{
                            __html: text || "-",
                          }}
                        />
                      ),
              });
            }
            item.label = item.title;
            return item;
          }),
        ];
        setFixedColumns(tmpColumns);
        setCheckedColumnKeys(checkedItems);
      } else if (configCode === MACRO_CONFIG_CODE) {
        let tmpColumns: any = genColumns("2");
        macroConfigName = res?.data[0]?.configName;
        macroConfigId = res?.data[0]?.id;
        // wtf
        macroColumnOptions = [
          ...configs?.map((item) => {
            if (item.checked) {
              checkedItems.push(item.value);
              tmpColumns.push({
                title: item.title,
                dataIndex: item.value,
                key: item.value,
                width: item.title === "日期" ? 120 : undefined,
                render:
                  item.title === "日期"
                    ? undefined
                    : (text: string) => (
                        <div
                          className={cn(
                            styles.editorDisplay,
                            "editor-description"
                          )}
                          style={{
                            minWidth:
                              item.title === "分析逻辑" ? "30vw" : "2vw",
                          }}
                          dangerouslySetInnerHTML={{
                            __html: text || "-",
                          }}
                        />
                      ),
              });
            }
            item.label = item.title;
            return item;
          }),
        ];
        setMacroColumns(tmpColumns);
        setCheckedMacroColumnKeys(checkedItems);
      }
    });
  };

  // 查询货币可选项
  const handleQueryMonetaryOptions = () => {
    queryMonetaryDate().then((res) => {
      if (res?.code == 0) {
        let arr = Object.keys(res?.data).map((v) => {
          return {
            key: v,
            label: v,
          };
        });
        setMonetaryOptions(arr);
        if (monetaryOptions?.length == 0 && arr.length > 0) {
          setSelectMonetaryOptions([arr[0]?.key]);
        }
      }
    });
  };

  useEffect(() => {
    queryBroker().then((res) => {
      let tmpOptions = [];
      Object.keys(res?.data).forEach((key, index) => {
        tmpOptions.push({
          label: key,
          value: key,
        });
      });
      setBrokerOptions(tmpOptions);
    });

    // 查询宏观券商
    queryMacroBroker().then((res) => {
      let tmpOptions = [];
      Object.keys(res?.data).forEach((key, index) => {
        tmpOptions.push({
          label: key,
          value: key,
        });
      });
      setBrokerMacroOptions(tmpOptions);
    });

    getConfig(FIXED_CONFIG_CODE);
    getConfig(MACRO_CONFIG_CODE);
    handleQueryMonetaryOptions();
  }, []);

  // 查固收观点
  const handleQueryFixAssets = useCallback(() => {
    setLoadingBroker(true);
    selectList({
      broker: saveParams.broker,
      middleFlag: saveParams.middleFlag,
      shortFlag: saveParams.shortFlag,
      endDate: end ? dayjs(end).format("YYYY-MM-DD") : "",
      startDate: start ? dayjs(start).format("YYYY-MM-DD") : "",
    }).then((res) => {
      // console.log(res);
      setFixedIncomeList(res.data);
      setLoadingBroker(false);
    });
  }, [
    start,
    end,
    saveParams.broker,
    saveParams.shortFlag,
    saveParams.middleFlag,
  ]);

  // 查询卖方固收日期
  const handleQueryBrokerDate = () => {
    queryBrokerDate().then((res) => {
      if (res?.code == 0) {
        setStart(res?.data ? dayjs(res?.data) : "");
        setEnd(res?.data ? dayjs(res?.data) : "");
      }
    });
  };

  // 查询卖方宏观日期
  const handleQueryMacroBrokerDate = () => {
    queryMacroBrokerDate().then((res) => {
      if (res?.code == 0) {
        setMacroStart(res?.data ? dayjs(res?.data) : "");
        setMacroEnd(res?.data ? dayjs(res?.data) : "");
      }
    });
  };

  useEffect(() => {
    handleQueryBrokerDate();
    handleQueryMacroBrokerDate();
  }, []);

  useEffect(() => {
    if (start) {
      // 时间不给清空，用来判断有值后查询
      handleQueryFixAssets();
    }
  }, [handleQueryFixAssets, start]);

  // 查宏观观点
  const handleQueryMacro = useCallback(() => {
    setLoadingMacroBroker(true);
    macro_selectList({
      broker: saveParams.macroBroker,
      endDate: macroEnd ? dayjs(macroEnd).format("YYYY-MM-DD") : "",
      startDate: macroStart ? dayjs(macroStart).format("YYYY-MM-DD") : "",
    }).then((res) => {
      setMacroList(res.data);
      setLoadingMacroBroker(false);
    });
  }, [macroEnd, macroStart, saveParams.macroBroker]);
  useEffect(() => {
    if (macroStart) {
      // 时间不给清空，用来判断有值后查询
      handleQueryMacro();
    }
  }, [macroStart, handleQueryMacro]);

  // 查货币政策对比
  const handleQueryMonetary = () => {
    setLoadingMonetary(true);
    queryMonetaryReportTable({
      reportDates: selectMonetaryOptions,
    }).then((res) => {
      setLoadingMonetary(false);
      if (res?.code == 0) {
        // 计算折叠行
        if (res?.data?.table) {
          res.data.table.shift();
          let obj = {};
          // let flag = false;
          let sameIndex = 0;
          res?.data?.table.map((v, index) => {
            if (obj[v["一级类别"]]) {
              // flag = false;
              obj[v["一级类别"]] = obj[v["一级类别"]] + 1;
              v.rowspan = false;
              v.sameIndex = sameIndex;
            } else {
              // flag = true;
              obj[v["一级类别"]] = 1;
              v.sameIndex = index;
              sameIndex = index;
              v.rowspan = true;
            }
          });
          setMaxIndex(sameIndex);

          const columns = res.data?.title?.map((v) => {
            return {
              title: ["一级类别", "二级类别"].includes(v) ? (
                v
              ) : (
                <div>
                  {v}{" "}
                  {isAuthored("EDIT_DELETE") && (
                    <TableOptBtn
                      img={icon_edit}
                      style={{ marginRight: "16px" }}
                      text=""
                      onClick={() => addEvent(true, "3", { reportDate: v })}
                    />
                  )}
                </div>
              ),
              dataIndex: v,
              key: v,
              fixed: ["一级类别", "二级类别"].includes(v),
              width: ["一级类别", "二级类别"].includes(v)
                ? 140
                : "calc(100% - 280px)",
              render: (item: string) => (
                <div
                  className={cn(styles.editorDisplay, "editor-description")}
                  dangerouslySetInnerHTML={{
                    __html: item || "-",
                  }}
                  style={{
                    minWidth: ["一级类别", "二级类别"].includes(v) ? 80 : 300,
                    fontWeight: v == "一级类别" ? 600 : 400,
                    opacity: v == "一级类别" ? 0.7 : 1,
                  }}
                />
              ),
              onCell: (row) => {
                if (v === "一级类别") {
                  if (row.rowspan) {
                    return { rowSpan: obj[row["一级类别"]] };
                  }
                  if (!row.rowspan) {
                    return { rowSpan: 0 };
                  }
                }
                return {};
              },
            };
          });
          setMonetaryColumns(columns);

          setMonetaryReportTable(res.data.table);
        } else {
          setMonetaryReportTable([]);
        }
      }
    });
  };

  useEffect(() => {
    handleQueryMonetary();
  }, [selectMonetaryOptions]);

  // 查询，新增或者编辑后使用
  const handleQuery = () => {
    console.log(baseDrawerProps);

    if (baseDrawerProps.title === "1") {
      if (baseDrawerProps.id) {
        handleQueryFixAssets();
      } else {
        handleQueryBrokerDate();
      }
    } else if (baseDrawerProps.title === "2") {
      if (baseDrawerProps.id) {
        handleQueryMacro();
      } else {
        handleQueryMacroBrokerDate();
      }
    } else {
      handleQueryMonetary();
      handleQueryMonetaryOptions();
    }
  };

  // console.log(baseDrawerProps);

  const cusRowClassName = (record: any, index: number): string => {
    // console.log(record);

    let str = "";
    if (record.rowspan) {
      str =
        "rowspan-td grey-td-1 grey-td-2 " +
        "gf_" +
        record.sameIndex +
        (record.sameIndex == maxIndex ? " last-fir-row" : "");
    } else if (record.rowspan === false) {
      str = "grey-td-1 " + "gf_" + record.sameIndex;
    }
    return str;
  };

  // 控制hover行样式
  const onMoveTableRow = (record) => {
    // console.log(record);
    const dom1 = document.getElementsByClassName(`gf_${record.sameIndex}`);
    // console.log(dom1);

    if (!dom1 || dom1.length === 1) return;
    try {
      let targetTr: any = dom1[0].childNodes[0];
      // console.log(dom1[0], dom1[0].childNodes[0], dom1[0].childNodes[0].classList)
      if (!targetTr?.classList?.includes("ant-table-cell-row-hover")) {
        targetTr.add("ant-table-cell-row-hover");
      }
    } catch (error) {}
  };

  return (
    <PageWrapper narrow minWidth={"1150px"}>
      <EditEventStrategy
        title={baseDrawerProps?.title}
        toggleDrawer={addEvent}
        visible={baseDrawerProps?.visible}
        handleQuery={handleQuery}
        {...baseDrawerProps}
      />
      <ErrorModal
        visible={deleteInfo.modalVisible}
        onCancel={() =>
          setDeleteInfo({
            modalVisible: false,
            errorMsg: "",
            deleteId: -1,
            deleteType: "0",
          })
        }
        onOk={deleteList}
        msg={deleteInfo.errorMsg}
        img={icon_error}
      />
      <Title style={{ marginLeft: 16 }}>卖方策略观点</Title>
      <TabWrapper>
        <Tabs activeKey={currentKey} onChange={callback}>
          {TABS.map((tab: tabProps) => (
            <TabPane tab={tab.title} key={tab.key}></TabPane>
          ))}
        </Tabs>
      </TabWrapper>

      <div className={styles.scrollBox} id="seller_box">
        <div className="observe_child" id="child_1">
          <LittleTitle title="卖方固收组观点汇总" mb="8px" />
          <SellerToolBar>
            <div style={{ display: "inline-flex" }}>
              <CusDatePicker
                startValue={start}
                endValue={end}
                onChange={(e, type) => handleDate(e, type, "fixed")}
                label="日期"
              />
              <Label>券商</Label>
              <Select
                style={{ width: 100 }}
                suffixIcon={<div className="findfit_icon_arrow " />}
                value={saveParams.broker}
                onChange={(e) => onChange(e, "broker")}
                options={brokerOptions}
                // iserror={errorList.includes("broker")}
                allowClear
                placeholder="请选择"
              ></Select>
              <Label>多空判断(短)</Label>
              <Select
                style={{ width: 100 }}
                suffixIcon={<div className="findfit_icon_arrow " />}
                value={saveParams.shortFlag}
                onChange={(e) => onChange(e, "shortFlag")}
                allowClear
                placeholder="请选择"
                options={flagOptions}
              ></Select>
              <Label>多空判断(中)</Label>
              <Select
                style={{ width: 100 }}
                suffixIcon={<div className="findfit_icon_arrow " />}
                value={saveParams.middleFlag}
                onChange={(e) => onChange(e, "middleFlag")}
                allowClear
                placeholder="请选择"
                options={flagOptions}
              ></Select>
            </div>

            <div style={{ display: "inline-flex" }}>
              <Popover
                content={
                  <SimpleColumnSelector
                    title="指标自定义"
                    columnOptions={fixedColumnOptions}
                    checkedValues={checkedColumnKeys}
                    changeColumns={changeColumns}
                    setPopoverVisible={setPopoverVisible}
                    // style={{ height: "108px" }}
                  ></SimpleColumnSelector>
                }
                visible={popoverVisible}
                placement="bottomRight"
                onVisibleChange={(visible) => {
                  setPopoverVisible(visible);
                }}
                overlayClassName={[styles.popoverStyle, styles.bond].join(" ")}
                overlayInnerStyle={{ width: 246 }}
                destroyTooltipOnHide={true}
                arrowPointAtCenter={true}
                trigger="click"
              >
                <SettingButton
                  style={{ marginLeft: 86 }}
                  icon={<img src={icon_setting} />}
                  onClick={() => {
                    setPopoverVisible(true);
                  }}
                />
              </Popover>
              <VerticleBar />
              <SettingButton
                icon={<img src={icon_download} />}
                opacity={0.8}
                onClick={() => {
                  exportData("fixed");
                }}
              />
              <VerticleBar />
              <BorderRedBtn onClick={() => addEvent(true, "1")}>
                <RedPlus />
                新增事件
              </BorderRedBtn>
            </div>
          </SellerToolBar>
          <FreeTable
            dataSource={{
              records: fixedIncomeList,
            }}
            className={styles.sellerTable}
            notShowPagination={true}
            rowKey={(r) => r.id}
            columns={fixedColumns}
            // onChange={changePage}
            style={{ whiteSpace: "nowrap", marginTop: 8, marginBottom: 32 }}
            scroll={{ x: true }}
            loading={loadingBroker}
          ></FreeTable>
        </div>
        <div className="observe_child" id="child_2">
          <LittleTitle title="卖方宏观组观点汇总" mb="8px" />
          <SellerToolBar>
            <div style={{ display: "inline-flex" }}>
              <CusDatePicker
                startValue={macroStart}
                endValue={macroEnd}
                onChange={(e, type) => handleDate(e, type, "macro")}
                label="日期"
              />
              <Label>券商</Label>
              <Select
                style={{ width: 100 }}
                suffixIcon={<div className="findfit_icon_arrow " />}
                value={saveParams.macroBroker}
                onChange={(e) => onChange(e, "macroBroker")}
                options={brokerMacroOptions}
                // iserror={errorList.includes("broker")}
                allowClear
                placeholder="请选择"
              ></Select>
            </div>
            <div style={{ display: "inline-flex" }}>
              <Popover
                content={
                  <SimpleColumnSelector
                    title="指标自定义"
                    columnOptions={macroColumnOptions}
                    checkedValues={checkedMacroColumnKeys}
                    changeColumns={changeMacroColumns}
                    setPopoverVisible={setMacroPopoverVisible}
                    // style={{ height: "108px" }}
                  ></SimpleColumnSelector>
                }
                visible={macroPopoverVisible}
                placement="bottomRight"
                onVisibleChange={(visible) => {
                  setMacroPopoverVisible(visible);
                }}
                overlayClassName={[styles.popoverStyle, styles.bond].join(" ")}
                overlayInnerStyle={{ width: 246 }}
                destroyTooltipOnHide={true}
                arrowPointAtCenter={true}
                trigger="click"
              >
                <SettingButton
                  icon={<img src={icon_setting} />}
                  onClick={() => {
                    setMacroPopoverVisible(true);
                  }}
                />
              </Popover>
              <VerticleBar />
              <SettingButton
                icon={<img src={icon_download} />}
                opacity={0.8}
                onClick={() => {
                  exportData("macro");
                }}
              />
              <VerticleBar />
              <BorderRedBtn onClick={() => addEvent(true, "2")}>
                <RedPlus />
                新增事件
              </BorderRedBtn>
            </div>
          </SellerToolBar>
          <FreeTable
            dataSource={{
              records: macroList,
            }}
            className={styles.sellerTable}
            notShowPagination={true}
            rowKey={(r) => r.id}
            columns={macroColumns}
            // onChange={changePage}
            style={{ whiteSpace: "nowrap", marginTop: 8, marginBottom: 32 }}
            scroll={{ x: true }}
            loading={loadingMacroBroker}
          ></FreeTable>
        </div>
        <div className="observe_child" id="child_3">
          <LittleTitle title="货币政策执行报告对比" mb="8px" />
          <SellerToolBar>
            <div style={{ display: "inline-flex" }}>
              {/* <Label>日期</Label> */}
              <CusSelectMulti
                Options={monetaryOptions}
                value={selectMonetaryOptions}
                onChange={setSelectMonetaryOptions}
                label="日期"
                style={{
                  width: "unset",
                  minWidth: 260,
                  maxWidth: "calc(100vw - 243px)",
                }}
              />
            </div>
            <div style={{ display: "inline-flex" }}>
              <SettingButton
                icon={<img src={icon_download} alt='download' />}
                opacity={0.8}
                onClick={() => {
                  exportData("monetary");
                }}
              />
              <VerticleBar />
              <BorderRedBtn onClick={() => addEvent(true, "3")}>
                <RedPlus />
                新增事件
              </BorderRedBtn>
            </div>
          </SellerToolBar>
          {!monetaryReportTable || monetaryReportTable?.length === 0 ? (
            <EventEmptyCom
              style={{ border: "1px solid #ced7e8", marginTop: 8 }}
              title="暂无数据"
            />
          ) : (
            <FreeTable
              dataSource={{
                records: monetaryReportTable,
              }}
              notShowPagination={true}
              rowKey={(r) => r.id}
              className={cn(styles.mergeTable)}
              columns={monetaryColumns}
              // onChange={changePage}
              style={{ whiteSpace: "nowrap", marginTop: 8, marginBottom: 32 }}
              scroll={{ x: true }}
              loading={loadingMonetary}
              rowClassName={cusRowClassName}
              onRow={(record) => {
                return {
                  onMouseEnter: (event) => {
                    onMoveTableRow(record);
                  }, // 鼠标移入行
                  onMouseLeave: (event) => {},
                };
              }}
            />
          )}
        </div>
      </div>
    </PageWrapper>
  );
}

const SellerToolBar = styled.div`
  height: 28px;
  width: 100%;
  min-width: 1068px;
  display: inline-flex;
  justify-content: space-between;
`;

const Label = styled.span`
  color: #35425e;
  height: 28px;
  opacity: 0.7;
  font-weight: 600;
  font-size: 13px;
  line-height: 28px;
  margin-left: 12px;
  margin-right: 8px;
`;

const TabWrapper = styled.div`
  margin-top: 16px;
  .ant-select-show-search.ant-select:not(.ant-select-customize-input)
    .ant-select-selector {
    min-width: 150px;
    max-width: 280px;
  }

  .ant-tabs-nav {
    margin-bottom: 0;
  }

  .ant-tabs-tab.ant-tabs-tab-active .ant-tabs-tab-btn {
    font-size: 14px;
    font-weight: bold;
    color: #1f51a4;
  }

  .ant-tabs-tab-btn {
    color: #35425e;
    font-size: 14px;
  }

  .ant-tabs-tab-btn:hover {
    color: #1f51a4;
  }

  .ant-tabs-tab:hover {
    color: #1f51a4;
  }

  .ant-tabs-tab {
    padding: 8px 0;
  }

  .ant-tabs-ink-bar {
    background-color: #1f51a4;
  }

  .ant-tabs-ink-bar:hover {
    .ant-tabs-tab-btn {
      color: #1f51a4;
    }
  }
`;

const SettingButtonContent = ({
  className,
  style,
  children,
  onClick,
  loading,
  icon,
}) => (
  <Button
    className={className}
    style={style}
    onClick={onClick}
    loading={loading}
    icon={icon}
  >
    {children}
  </Button>
);

const SettingButton = styled(SettingButtonContent)`
  height: 28px;
  width: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(245, 246, 248, 1);
  border-radius: 2px;
  border: none;
  box-shadow: none;
  margin-bottom: 4px;
  &:hover {
    background: rgba(248, 249, 252, 1);
  }

  &:active {
    background: rgba(236, 238, 242, 1);
  }

  > img {
    width: 14px;
    height: 14px;
    display: inline-block;
    background-position: 50%;
    background-size: 100% auto;
    background-repeat: no-repeat;
    opacity: ${(props) => (props.opacity ? props.opacity : 0.7)};
  }
`;

export const VerticleBar = styled.div`
  width: 1px;
  height: 16px;
  background: #e4e4e4;
  position: relative;
  margin: 0 8px;
  top: 50%;
  margin: 0 8px;
  transform: translateY(-50%);
`;
